package com.whu.waterworks.service;

import java.util.List;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import com.whu.waterworks.dao.WaterUserDAO;
import com.whu.waterworks.model.WaterUser;

public class WaterWorksUserService {
	private WaterUserDAO waterUserDAO;

	public WaterUser getUserByName(String userName) {
		return waterUserDAO.findByName(userName);
	}

	public Boolean updateUser(WaterUser waterUser) {
		WaterUser temp = waterUserDAO.update(waterUser);
		if (temp == null) {
			return false;
		}
		return null;
	}

	public Boolean updateUserPassword(String oldPassword, String newPassword,
			String secondPassword) {
		Boolean is = false;

		if (newPassword.equals(secondPassword)) {
			Authentication auth = SecurityContextHolder.getContext()
					.getAuthentication();
			if (auth.getPrincipal() instanceof UserDetails) {
				UserDetails userDetails = (UserDetails) auth.getPrincipal();
				if (waterUserDAO.findByName(userDetails.getUsername()).getPassword().equals(oldPassword)) {
					WaterUser waterUser = getUserByName(userDetails.getUsername());
					waterUser.setPassword(newPassword);
					updateUser(waterUser);
					is=true;
				}
				
			}
		}
		return is;
	}
	
	public Boolean addUser(WaterUser waterUser) {
	     boolean result = false;
	     try {
	    	 waterUserDAO.save(waterUser);
	    	 result =true;
		} catch (Exception e) {
			result =false;
		}
	     
	     return result;
	}

	public Boolean deleteUserByUsername(String username) {
	     boolean result = false;
	     WaterUser temp= getUserByName(username);
	     try {
	    	 waterUserDAO.delete(temp);
	    	 result =true;
		} catch (Exception e) {
			result =false;
		}
	     
	     return result;
	}

	public List<WaterUser> getAllUsers() {
		return waterUserDAO.findAll();
	}

	public WaterUserDAO getWaterUserDAO() {
		return waterUserDAO;
	}

	public void setWaterUserDAO(WaterUserDAO waterUserDAO) {
		this.waterUserDAO = waterUserDAO;
	}
}
